/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.BluetoothChat;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

	
 /** This is the main Activity that displays the current chat session.
 */
public class BluetoothChat extends Activity {
    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Layout Views
    private TextView mTitle;
    private ListView mConversationView;
    private EditText mOutEditText;
    private Button mSendButton;
    private Button mWriteButton;
    private EditText pitchP,pitchI, pitchD, ratePitch, version2;
    private EditText yawP,yawI,yawD, rateYaw;
    private EditText altP,altI,altD;
    private EditText rcrate, rcexpo,dynpidatt;
    private EditText altvelP,altvelI,altvelD,gpsP,gpsI,gpsD;
    private EditText levelP,levelI,levelD,magP;

    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    private static ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;

    
    
    //Serial g_serial;
    
    int CHECKBOXITEMS=11;
    int PIDITEMS=8;
    int commListMax;
    int frame_size_read = 108+3*PIDITEMS+2*CHECKBOXITEMS;
    int frame_size_write = 8+3*PIDITEMS+2*CHECKBOXITEMS;
    byte[] inBuf = new byte[frame_size_read+1];
   
    
 
    int windowsX    = 800;        int windowsY    = 540;
    int xGraph      = 10;         int yGraph      = 325;
    int xObj        = 700;        int yObj        = 450;
    int xParam      = 120;        int yParam      = 10;
    int xRC         = 650;        int yRC         = 15;
    int xMot        = 490;        int yMot        = 30;
    int xButton     = 485;        int yButton     = 185;
    int xBox        = xParam+190; int yBox        = yParam+70;

    boolean axGraph =true,ayGraph=true,azGraph=true,gxGraph=true,gyGraph=true,gzGraph=true,baroGraph=true,headGraph=true, magxGraph =true,magyGraph=true,magzGraph=true;
    boolean debug1Graph = false,debug2Graph = false,debug3Graph = false,debug4Graph = false;

    int multiType;  // 1 for tricopter, 2 for quad+, 3 for quadX, ...

  
    private static final int ROLL = 0, PITCH = 1, YAW = 2, ALT = 3, VEL = 4, LEVEL = 5, MAG = 6;

    int       byteP[] = new int[PIDITEMS],       byteI[] = new int[PIDITEMS],       byteD[] = new int[PIDITEMS];

   
    int  byteRC_RATE,byteRC_EXPO, byteRollPitchRate,byteYawRate, byteDynThrPID;

    boolean graphEnable = false;boolean readEnable = false;boolean writeEnable = false;boolean calibrateEnable = false;

    int version,versionMisMatch;
    float gx,gy,gz,ax,ay,az,magx,magy,magz,baro,head,angx,angy,debug1,debug2,debug3,debug4;
    int GPS_distanceToHome, GPS_directionToHome;
    int  GPS_numSat,GPS_fix,GPS_update;
    int init_com,graph_on,pMeterSum,intPowerTrigger,bytevbat;

    float mot[] = new float[8];
    float servo[] = new float[8];
    float rcThrottle = 1500,rcRoll = 1500,rcPitch = 1500,rcYaw =1500,
          rcAUX1=1500, rcAUX2=1500, rcAUX3=1500, rcAUX4=1500;
    int nunchukPresent,i2cAccPresent,i2cBaroPresent,i2cMagnetoPresent,GPSPresent,levelMode;

    float time1,time2;
    int cycleTime,i2cError;

    int activation1[] = new int[CHECKBOXITEMS];
    int activation2[] = new int[CHECKBOXITEMS];
    Button buttonCheckbox[] = new Button[CHECKBOXITEMS];
    String buttonCheckboxLabel[] = {   "LEVEL",  "BARO",  "MAG",  "CAMSTAB",  "CAMTRIG",  "ARM",  "GPS HOME",  "GPS HOLD",  "PASSTHRU",  "HEADFREE",  "BEEPER", }; 

    @Override
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");

        // Set up the window layout
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
       
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

        // Set up the custom title
        mTitle = (TextView) findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = (TextView) findViewById(R.id.title_right_text);

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }

    private void setupChat() {
        Log.d(TAG, "setupChat()");

        //Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);

        //Initialize the compose field with a listener for the return key
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        mOutEditText.setOnEditorActionListener(mWriteListener);
        
        //Initialize edittexts;
        
        version2 =(EditText) findViewById(R.id.version2);
        pitchP = (EditText) findViewById(R.id.pitchP);
        pitchI = (EditText) findViewById(R.id.pitchI);
        pitchD = (EditText) findViewById(R.id.pitchD);
        yawP = (EditText) findViewById(R.id.yawP);
        yawI = (EditText) findViewById(R.id.yawI);
        yawD = (EditText) findViewById(R.id.yawD);
        altP= (EditText) findViewById(R.id.altP);
    	altI= (EditText) findViewById(R.id.altI);
    	altD= (EditText) findViewById(R.id.altD);
    	altvelP= (EditText) findViewById(R.id.altvelP);
    	altvelI= (EditText) findViewById(R.id.altvelI);
    	altvelD= (EditText) findViewById(R.id.altvelD);
    	levelP= (EditText) findViewById(R.id.levelP);
    	levelI= (EditText) findViewById(R.id.levelI);
    	levelD= (EditText) findViewById(R.id.levelD);
    	magP= (EditText) findViewById(R.id.magP);
    	gpsP= (EditText) findViewById(R.id.gpsP);
    	gpsI= (EditText) findViewById(R.id.gpsI);
    	gpsD= (EditText) findViewById(R.id.gpsD);
        ratePitch=(EditText) findViewById(R.id.ratePitch);
        rateYaw=(EditText) findViewById(R.id.rateYaw);	
        dynpidatt=(EditText) findViewById(R.id.dynpidatt);
        rcexpo=(EditText) findViewById(R.id.rcexpo);
        rcrate=(EditText) findViewById(R.id.rcrate);
        
        
        //Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                message = "M";
                sendMessage(message);
            }
        });
        //Initialize the write button with a listener
        mWriteButton = (Button) findViewById(R.id.button_write);
        mWriteButton.setOnClickListener(new OnClickListener() {
        int outBuff=0;    
        	public void onClick(View v) {
                //Send a message using content of the edit text widget
                //TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message;
                String a =  pitchP.getText().toString();
                byteP[0]= Integer.parseInt(pitchP.getText().toString()) ;
              	byteI[0]= Integer.parseInt(pitchI.getText().toString())*1000;
              	byteD[0]= Integer.parseInt(pitchD.getText().toString());
              	byteP[1]= Integer.parseInt(pitchP.getText().toString())*10 ;
              	byteI[1]= Integer.parseInt(pitchI.getText().toString())*1000;
              	byteD[1]= Integer.parseInt(pitchD.getText().toString());
              	byteP[2]= Integer.parseInt(yawP.getText().toString())*10 ;
    			byteI[2]=Integer.parseInt(yawI.getText().toString())*1000 ;
    			byteD[2]=Integer.parseInt(yawD.getText().toString()) ;
    			byteP[3]=Integer.parseInt(altP.getText().toString())*10 ;
    			byteI[3]=Integer.parseInt(altI.getText().toString())*1000 ;
    			byteD[3]=Integer.parseInt(altD.getText().toString()) ;
    			byteP[4]=Integer.parseInt(altvelP.getText().toString())*10 ;
    			byteI[4]=Integer.parseInt(altvelI.getText().toString())*1000 ;
    			byteD[4]=Integer.parseInt(altvelD.getText().toString()) ;
    			byteP[5]=Integer.parseInt(gpsP.getText().toString())*10 ;
    			byteI[5]=Integer.parseInt(gpsI.getText().toString())*1000 ;
    			byteD[5]=Integer.parseInt(gpsD.getText().toString()) ;
    			byteP[6]=Integer.parseInt(levelP.getText().toString())*10 ;
    			byteI[6]=Integer.parseInt(levelI.getText().toString())*1000 ;
    			byteD[6]=Integer.parseInt(levelD.getText().toString()) ;
    			byteP[7]=Integer.parseInt(magP.getText().toString())*10 ;
              	byteRC_RATE =Integer.parseInt(rcrate.getText().toString())*50;
    			byteRC_EXPO = Integer.parseInt(rcexpo.getText().toString())*100;
    			byteRollPitchRate = Integer.parseInt(ratePitch.getText().toString())*100;
    			byteYawRate = Integer.parseInt(rateYaw.getText().toString())*100;
    			byteDynThrPID =Integer.parseInt(dynpidatt.getText().toString())*100;
    			/*for(int i=0;i<CHECKBOXITEMS;i++) {
    			    activation1[i] = 0;
    			    activation2[i] = 0;
    			for(int a=0;a<6;a++) {
    			      activation1[i] += (int)(checkbox1[i].arrayValue()[a]*(1<<a));
    			      activation2[i] += (int)(checkbox2[i].arrayValue()[a]*(1<<a));
    			    }
    			  }*/
    			  //intPowerTrigger = (round(confPowerTrigger.value()));

    			  int[] s = new int[frame_size_write];
    			  int p = 0;
    			   s[p++] = 'W'; //0 write to Eeprom @ arduino //1
    			   for(int i=0;i<PIDITEMS;i++) {s[p++] = byteP[i];  s[p++] = byteI[i];  s[p++] =  byteD[i];} //16
    			   s[p++] = byteRC_RATE; s[p++] = byteRC_EXPO; 
    			   s[p++] = byteRollPitchRate; 
    			   s[p++] = byteYawRate;
    			   s[p++] = byteDynThrPID; //24
    			   for(int i=0;i<CHECKBOXITEMS;i++) {s[p++] = activation1[i];s[p++] = activation2[i];}
    			   s[p++] = intPowerTrigger;
    			   s[p++] = intPowerTrigger >>8 &0xff;
    			   for(int i =0;i<frame_size_write;i++){
    				   outBuff= outBuff+s[i];}
    			   
                message = String.valueOf(outBuff);
                sendMessage(message);
                }
               
        	});
          
        
        
        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }

    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            mOutEditText.setText(mOutStringBuffer);
        }
    }

    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };
    
   
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        
        @Override
        
        public void handleMessage(Message msg) {
           
			switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                    mConversationArrayAdapter.clear();
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothChatService.STATE_LISTEN:
                case BluetoothChatService.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
                
                
                
            case MESSAGE_READ:
            	byte[] b =  (byte[]) msg.obj;
            	int w;
            	for (w=0; w<frame_size_read+1; w++) {
            		   inBuf[w]=b[w];
            		}
            	processSerialData();
            	
            	version2.setText(String.valueOf(version));
            	pitchP.setText(String.valueOf(byteP[0]/10f));
            	pitchI.setText(String.valueOf(byteI[0]/1000f));
            	pitchD.setText(String.valueOf(byteD[0]));
            	yawP.setText(String.valueOf(byteP[2]/10f));
            	yawI.setText(String.valueOf(byteI[2]/1000f));
            	yawD.setText(String.valueOf(byteD[2]));
            	altP.setText(String.valueOf(byteP[3]/10f));
            	altI.setText(String.valueOf(byteI[3]/1000f));
            	altD.setText(String.valueOf(byteD[3]));
            	altvelP.setText(String.valueOf(byteP[4]/10f));
            	altvelI.setText(String.valueOf(byteI[4]/1000f));
            	altvelD.setText(String.valueOf(byteD[4]));
            	levelP.setText(String.valueOf(byteP[6]/10f));
            	levelI.setText(String.valueOf(byteI[6]/1000f));
            	levelD.setText(String.valueOf(byteD[6]));
            	magP.setText(String.valueOf(byteP[7]/10f));
            	gpsP.setText(String.valueOf(byteP[5]/10f));
            	gpsI.setText(String.valueOf(byteI[5]/1000f));
            	gpsD.setText(String.valueOf(byteD[5]));
            	rcrate.setText(String.valueOf(byteRC_RATE/50f));
            	rcexpo.setText(String.valueOf(byteRC_EXPO/100f));
            	dynpidatt.setText(String.valueOf(byteDynThrPID/100f));
                rateYaw.setText(String.valueOf(byteYawRate/100f));
            	ratePitch.setText(String.valueOf(byteRollPitchRate/100f));
            	break;
                
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
        	
           	int p;
    		 		
    		
        	public int read16() {return (inBuf[p++]&0xff) + (inBuf[p++]<<8);}
    		public int read8()  {return inBuf[p++]&0xff;}
    		
    		
    		
    		
    		
    		public void processSerialData() {
    				int present=0,mode=0;
    	  	
    				p=0;
    				char who=(char) read8();
    				version = read8(); //version is read even if buffer length doesn't check          //1
    				//versionMisMatch = 0;
    				//if (String.valueOf(inBuf[frame_size_read-1]) == "M") {  // Multiwii @ arduino send all data to GUI
    				  ax = read16();ay = read16();az = read16();
    			      gx = read16()/8;gy = read16()/8;gz = read16()/8;                                //13
    			      magx = read16()/3;magy = read16()/3;magz = read16()/3;                          //19
    			      baro = read16();
    			      head = read16();                                                                //23
    			      for(int i=0;i<8;i++) servo[i] = read16();
    			      for(int i=0;i<8;i++) mot[i] = read16();
    			      rcRoll = read16();rcPitch = read16();rcYaw = read16();rcThrottle = read16();    
    			      rcAUX1 = read16();rcAUX2 = read16();rcAUX3 = read16();rcAUX4 = read16();
    			      present = read8(); 
    			      mode = read8();
    			      cycleTime = read16();
    			      i2cError = read16();
    			      angx = read16()/10;angy = read16()/10;
    			      multiType = read8();                                                            
    			      for(int i=0;i<PIDITEMS;i++) {byteP[i] = read8();byteI[i] = read8();byteD[i] = read8();}
    			      byteRC_RATE = read8();
    			      byteRC_EXPO = read8();
    			      byteRollPitchRate = read8();
    			      byteYawRate = read8();
    			      byteDynThrPID = read8();                                                        
    			      for(int i=0;i<CHECKBOXITEMS;i++) {activation1[i] = read8();activation2[i] = read8();}
    			      GPS_distanceToHome = read16();
    			      GPS_directionToHome = read16();
    			      GPS_numSat = read8();
    			      GPS_fix = read8();
    			      GPS_update = read8();
    			      pMeterSum = read16();
    			      intPowerTrigger = read16();
    			      bytevbat = read8();
    			      debug1 = read16();debug2 = read16();debug3 = read16();debug4 = read16();
    			      
    			      if ((present&1) >0) nunchukPresent = 1;    else  nunchukPresent = 0;
    			      if ((present&2) >0) i2cAccPresent = 1;     else  i2cAccPresent = 0;
    			      if ((present&4) >0) i2cBaroPresent = 1;    else  i2cBaroPresent = 0;
    			      if ((present&8) >0) i2cMagnetoPresent = 1; else  i2cMagnetoPresent = 0;
    			      if ((present&16)>0) GPSPresent = 1;        else  GPSPresent = 0;
    			     
    			   // } //else {
    			      //versionMisMatch = 1;
    			      //g_serial.readStringUntil('M');
    			    }
    		};
    	
    	  
       

    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mChatService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupChat();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.insecure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        }
        return false;
    }
    

}